import { Injectable } from '@angular/core';
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class WebSocketService {
  ws: WebSocket
  constructor() { }
  createObservableSocket(url: string, id: number): Observable<any> {
    this.ws = new WebSocket(url)
    return new Observable(
      observer => {
        this.ws.onmessage = (event) => observer.next(event.data)
        this.ws.onerror = (event) => observer.error(event)
        this.ws.onclose = (event) => observer.complete()
        this.ws.onopen = (event) => { this.sendMessage({ productId: id }) }
        return () => {
          this.ws.close()
        }
      }
    )
    // .pipe(map(message => {
    //   console.log(message)
    //   return JSON.parse(message + '')
    // }))
  }
  sendMessage(message: any) {
    this.ws.send(JSON.stringify(message))
  }
}
